package com.videoplayer;

import java.io.File;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.application.VideosList;
import com.db.DBConnect;
import com.lib.SlidingMenu;
import com.lib.SlidingView.isShow;
import com.services.aidl.IDownLoadService;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.util.ConfirmDialog;
import com.videoplayer.LeftFragment.ChangeList;

public class MainActivity extends FragmentActivity implements OnClickListener,
		ChangeList {

	private static final String SERVICE_ACTION = "com.service.download_service";
	private final String DB_GET_SHARPNESS = "name = 'count'";

	SlidingMenu mSlidingMenu;
	LeftFragment leftFragment;
	SampleListFragment centerFragment;
	private DBConnect dbCon;
	private IDownLoadService downloadService;
	private VideosList videoList;
	private Intent intent;
	private int count = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		IntentFilter counterActionFilter = new IntentFilter(
				"com.services.download");
		registerReceiver(counterActionReceiver, counterActionFilter);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		videoList = (VideosList) MainActivity.this.getApplicationContext();
		setContentView(R.layout.main);
		dbCon = new DBConnect(this);
		dbCon.open();
		try {
			dbCon.queryOneData(DB_GET_SHARPNESS);
			Log.e("count", dbCon.queryOneData(DB_GET_SHARPNESS)
					+ "***************************");
			dbCon.addCount();
		} catch (Exception e) {
			dbCon.insert(2, 0, 1);
			Intent i = new Intent();
			i.setClass(MainActivity.this, WelcomeActivity.class);
			startActivity(i);
		}
		// int count = dbCon.queryOneData("count");
		dbCon.close();
		File f = new File(Environment.getExternalStorageDirectory()
				+ "/EazyPlay/Cache/");
		if (!f.exists()) {
			f.mkdirs();
		}

		mSlidingMenu = (SlidingMenu) findViewById(R.id.slidingMenu);
		mSlidingMenu.setLeftView(getLayoutInflater().inflate(
				R.layout.left_frame, null));
		mSlidingMenu.setCenterView(getLayoutInflater().inflate(
				R.layout.center_frame, null));
		intent = new Intent(SERVICE_ACTION);
		bindService(intent, sConnect, Context.BIND_AUTO_CREATE);

		FragmentTransaction t = this.getSupportFragmentManager()
				.beginTransaction();
		leftFragment = new LeftFragment();
		t.replace(R.id.left_frame, leftFragment);

		centerFragment = new SampleListFragment();
		t.replace(R.id.center_frame, centerFragment);
		t.commit();

		mSlidingMenu.mSlidingView.setIsShow(new isShow() {

			@Override
			public void doShow() {
				// TODO Auto-generated method stub
				Log.v("show", "show!!!!!!!!!!!!!!!!!!!!!!!!!");
				centerFragment.imm.hideSoftInputFromWindow(centerFragment.etSearch.getWindowToken(), 0);
				centerFragment.lvVideo.setEnabled(false);
				centerFragment.ivCover.setVisibility(View.VISIBLE);
			}

			@Override
			public void doHide() {
				// TODO Auto-generated method stub
				Log.v("hide", "hide########################");
				centerFragment.lvVideo.setEnabled(true);
				centerFragment.ivCover.setVisibility(View.GONE);
			}

		});

	}

	UmengUpdateListener updateListener = new UmengUpdateListener() {
		@Override
		public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
			switch (updateStatus) {
			case 0: // has update
				Log.i("--->", "callback result");
				UmengUpdateAgent
						.showUpdateDialog(MainActivity.this, updateInfo);
				break;
			case 1: // has no update
				break;
			case 2: // none wifi
				break;
			case 3: // time out
				break;
			}

		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	private ServiceConnection sConnect = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i("ServiceConnection", "onServiceDisconnected() called");
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// 绑定到服务
			Log.i("ServiceConnection", "onServiceConnected() called");
			downloadService = IDownLoadService.Stub.asInterface(service);
		}
	};

	private BroadcastReceiver counterActionReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			int counter = intent.getIntExtra("id", 0);
			downloadList(counter);
		}

	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!centerFragment.lvVideo.isEnabled()) {
				showLeft();
				return true;
			}
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意
			intent.addCategory(Intent.CATEGORY_HOME);
			this.startActivity(intent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void downloadList(int id) {

		int length = videoList.getDownloadList().size();
		Log.v("id$$length", "^^^^^^id= " + id + "  length=  " + length);
		if (id < length - 1) {
			try {
				downloadService.down(videoList.getDownloadList().get(id + 1));
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void showLeft() {
		mSlidingMenu.showLeftView();
	}

	public void showRight() {
		mSlidingMenu.showRightView();
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if (centerFragment.lvVideo.isEnabled()) {
				showLeft();
				leftFragment.lvNavigation.setSelection(0);
				leftFragment.lvNavigation.requestFocus();
			}
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if (!centerFragment.lvVideo.isEnabled()) {
				showLeft();
				leftFragment.lvNavigation.setFocusable(false);
			}
			break;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(sConnect);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(0==count){
		UmengUpdateAgent.update(this);
		com.umeng.common.Log.LOG = true;
		UmengUpdateAgent.setUpdateAutoPopup(false);
		UmengUpdateAgent.setUpdateListener(updateListener);
		}
		count++;
		MobclickAgent.onResume(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		default:
			break;
		}
	}

	@Override
	public void Change(String url) {
		// TODO Auto-generated method stub
		centerFragment.AsyncChange(url);
	}

}
